<template>
  <div style="height: 100%;width: 100%;">

    <div id="mdEditorIDE" style="position: relative;border-radius: 10px">
      <div style="position: absolute;z-index: 999;top: 80px;right: 3%;">
        <el-progress
            class="bjs-progress"
            type="circle"
            :color="saveTask.lastSave === 'SUCCESS' ? 'rgba(104,184,40,0.3)' : 'rgba(255,0,15,0.5)'"
            :width="50"
            :show-text="false"
            :percentage="saveTask.progressValue"
        >
        </el-progress>
        <div class="show-info-btn"
             @contextmenu.prevent="showTocm()"
             @click="showInfo()">
          {{saveTask.clock}}
        </div>
        <div id="tocCustomContainer" class="toc-container" :style="tocm.visible"></div>
      </div>
    </div>

    <el-drawer
        title="文章信息"
        direction="rtl"
        class="bjs-drawer"
        :modal="false"
        :visible.sync="infoDrawerVisible">
      <articleInfo ref="refArticleInfo" :readOnly="true"></articleInfo>
    </el-drawer>
  </div>
</template>

<script>
import $ from "jquery";
import { getDraftOne, putDraftContent } from "../../../api/article"
import articleInfo from "../article/info"

export default {
  name:"mdEditor",
  data:function(){
    return {
      // 最终生成的编辑器
      editor: null,
      // 默认选项
      defaultOptions:{
        // theme : this.theme === 'light' ? 'default' : 'dark',
        // previewTheme : this.theme === 'light' ? 'default' : 'dark',
        // editorTheme : this.theme === 'light' ? 'default' : 'lesser-dark',
        width               : '99%',
        height              : '97%',
        path                : '../../../static/editor.md-master/lib/',
        markdown            : '',
        codeFold            : true,
        emoji               : true,
        taskList            : true,
        tocm                : true, // Using [TOCM]
        tocDropdown         : false,
        tocContainer        :'#tocCustomContainer',
        tex                 : false, // 开启科学公式TeX语言支持，默认关闭
        searchReplace       : true,
        saveHTMLToTextarea  : true, // 保存 HTML 到 Textarea
        htmlDecode          : 'style,script,iframe|on*',            // 开启 HTML 标签解析，为了安全性，默认不开启
        onchange : () => {
          this.contentChange()
        },
        onload: () => {
          let keyMap = {
            /**
             * @param cm codeMirror
             */
            // eslint-disable-next-line
            'Ctrl-S': (cm) => {
              this.save('MANUAL')
            }
          }
          this.editor.addKeyMap(keyMap)
        }
      },
      saveTask: {
        interval : null,          // 定时任务
        flag: false,              // 是否执行保存 true:保存 false:不保存
        clock:  0,                // 时钟
        progressValue : 0,        // 进度条 100则满
        // rgba(104,184,40,0.3)  (绿色成功)
        // rgba(255,0,15,0.5)    (保存失败)
        lastSave : 'SUCCESS'
      },
      // 文章内容
      infoDrawerVisible: false,
      articleInfo: {
        articleId: null
      },
      tocm: {
        visible: {
          'opacity':0
        }
      }
    }
  },
  mounted(){
    this.changeTheme()
    this.initMdEditor()
  },
  destroyed () {
    this.save()
  },
  components : {
    articleInfo
  },
  watch : {
    theme () {
      this.changeTheme()
    }
  },
  computed: {
    theme () {return this.$store.state.config.theme.type}
  },
  methods:{
    changeTheme () {
      if (this.theme === 'night') {
        this.defaultOptions.theme        = 'dark';
        this.defaultOptions.previewTheme = 'dark';
        this.defaultOptions.editorTheme = 'lesser-dark'
        if (this.editor != null) {
          this.editor.setTheme('dark')
          this.editor.setPreviewTheme('dark')
          this.editor.setEditorTheme('lesser-dark')
        }
      } else if (this.theme === 'light') {
        this.defaultOptions.theme        = 'default';
        this.defaultOptions.previewTheme = 'default';
        this.defaultOptions.editorTheme = 'default'
        if (this.editor != null) {
          this.editor.setTheme('default')
          this.editor.setPreviewTheme('default')
          this.editor.setEditorTheme('default')
        }
      }
    },
    contentChange(){
      this.saveTask.flag = true
    },
    showInfo(){
      if (this.$refs.refArticleInfo) {
        this.$refs.refArticleInfo.loadingTrue()
      }
      this.infoDrawerVisible = true
      this.$nextTick(() => {
        this.$refs.refArticleInfo.updInit(this.articleInfo)
      })
    },
    showTocm () {
      if (this.tocm.visible.opacity === 0) {
        this.tocm.visible.opacity = 1;return
      }
      this.tocm.visible.opacity = 0
    },
    save (type) {
      let param = {
        articleId   : this.articleInfo.articleId,
        contentMd   : this.editor.getMarkdown(),
        contentHtml : this.editor.getHTML(),
        saveType    : type
      }

      if (this.saveTask.flag) {
        // eslint-disable-next-line no-unused-vars
        putDraftContent(param).then(resp => {
          this.$bjsNotify.success('保存成功')
          this.saveTask.flag = false
          this.saveTask.lastSave = 'SUCCESS'
        }).catch(() => {
          this.saveTask.lastSave = 'ERROR'
        })
      }
    },
    saveTaskRun () {
      this.saveTask.clock ++
      let now = this.saveTask.progressValue + 0.33
      if (now >= 100) {
        this.saveTask.progressValue = 0
        this.saveTask.clock = 0
        this.save('AUTO')
      } else {
        if (this.saveTask.clock % 3 === 0) {
          this.saveTask.progressValue = Math.ceil(now)
        } else {
          this.saveTask.progressValue = now
        }
      }
      // console.log(this.saveTask.clock+' -> ',this.saveTask.progressValue)
    },
    saveTaskStart() {
      this.saveTask.interval = setInterval(this.saveTaskRun,1000);
    },
    saveTaskStop () {
      clearInterval(this.saveTask.interval)
    },
    initMdEditor(){
      this.articleInfo.articleId = this.$route.params.articleId

      getDraftOne({articleId: this.articleInfo.articleId, contentType:'MD'}).then(resp => {
        this.defaultOptions.markdown = resp.data.contentMd
        this.requireEditor(() => {
          // eslint-disable-next-line no-undef
          this.editor = editormd('mdEditorIDE',this.defaultOptions);
          this.saveTaskStart()
        });
      })
    },

































    // ───────────────────────────────────────────────────────── editormd ─────────────────────────────────────────────────────────
    /**
     * 异步加载editormd
     * callback 成功后的回调函数
     */
    requireEditor(callback){
      // eslint-disable-next-line no-unused-vars
      let vm = this;
      //设置全局变量，因为editormd依赖jquery
      window.$ = window.jQuery = $;
      //异步加载并执行
      $.getScript("/static/editor.md-master/editormd.min.js",() => {callback();});
      //加载css
      $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/static/editor.md-master/css/editormd.min.css'));
    },
    // ───────────────────────────────────────────────────────── editormd ─────────────────────────────────────────────────────────
  }
}
</script>

<style scoped lang="scss">
.bjs-editor {

}

.show-info-btn {
  @include flex(column,center,center);
  font-family: Lato;
  font-weight: bold;
  position: absolute;
  width: 48px;
  height: 48px;
  top: 48%;
  left: 50%;
  cursor: pointer;
  border-radius: 50%;
  color: $theme-color-light-dark;
  background-color: $theme-color-light-3;
  transition: 0.5s,background-color 0.3s;
  transform: translate(-50%,-50%);
  [data-theme="night"] & {
    color: $theme-color-night-dark;
    background-color: $theme-color-night-dark-3;
  }


  &:hover {
    background-color: $theme-color-light-7;
    [data-theme="night"] & {
      color: $theme-color-night;
      background-color: $theme-color-night-dark-5;
    }
  }
}

.bjs-progress {
  /deep/ .el-progress-circle {
    width: 60px !important;
    height: 60px !important;
  }

  /deep/ .el-progress-circle__track {
    [data-theme="night"] & {
      stroke: #4d4d3d !important;
    }
  }
}


.toc-container {
  position: absolute;
  top: 0;
  right: 110%;
  width: 350px;
  height: 500px;
  padding: 10px 10px;
  border: 1px solid rgb(221, 221, 221);
  border-radius: 5px;
  background-color: #eeeeee;
  [data-theme="night"] & {
    background-color: #181818;
    border: 1px solid  $theme-color-night-dark-5;
  }
  overflow-y: scroll;
  font-size: 13px;

  /deep/ ul {
    padding-inline-start: 20px;
  }

  /deep/ .toc-level-1,/deep/ .toc-level-2,/deep/ .toc-level-3,/deep/ .toc-level-4,/deep/ .toc-level-5,/deep/ .toc-level-6 {
    color: #7a7a7a !important;
  }
}
</style>
